// 修改umi默认的Webpack配置，build打包后，归类各类静态资源
const ASSETS_PREFIX = 'umi4CacheTemplate';

const ChainWebpack = (config) => {
  // 修改css输出目录
  config.plugin('mini-css-extract-plugin').tap((args) => [
    {
      ...args[0],
      filename: `${ASSETS_PREFIX}/css/[name].[contenthash:8].css`,
      chunkFilename: `${ASSETS_PREFIX}/css/[name].[contenthash:8].chunk.css`,
    },
  ]);

  // 修改js输出目录
  config.output
    .filename(`${ASSETS_PREFIX}/js/[name].[hash:8].js`)
    .chunkFilename(`${ASSETS_PREFIX}/js/[name].[contenthash:8].chunk.js`);

  // 修改image输出目录
  config.module
    .rule('images')
    .test(/\.(png|jpe?g|gif|webp|ico)(\?.*)?$/)
    .type('asset/resource')
    .generator({
      filename: `${ASSETS_PREFIX}/images/[name].[hash:8][ext]`,
    })
    .set('parser', {
      dataUrlCondition: {
        maxSize: 8 * 1024, //  小于8K的图片，转成base64
      },
    });

  // 修改svg输出目录
  config.module
    .rule('svg')
    .test(/\.(svg)(\?.*)?$/)
    .type('asset/resource')
    .generator({
      filename: `${ASSETS_PREFIX}/images/[name].[hash:8][ext]`,
    });

  // 修改font输出目录
  config.module
    .rule('fonts')
    .test(/\.(eot|woff|woff2|ttf)(\?.*)?$/)
    .type('asset/resource')
    .generator({
      filename: `${ASSETS_PREFIX}/fonts/[name].[hash:8][ext]`,
    });
};

export default ChainWebpack;
